define(function(require){
    $(function(){
    	/*---------- 用户管理——管理员 ----------*/

    	/* 表格 */
    	var org_id = semi.utils.getUrlParam('org_id');
    	var bodyTemplate = ['<tr user_id="{id}">',
	    	                    '<td class="txtc org_name">{username}</td>',
	    	                    '<td class="txtc org_phone">{phone}</td>',
	    	                    '<td class="txtc org_email">{email}</td>',
	    	                    '<td class="txtl org_description">{description}</td>',
		                     	'<td class="txtc">',
		                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
		                     		'<a class="ibtn resetbtn" href="javascript:;" title="重置密码"><span class="glyphicon glyphicon-repeat"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');
        
        var grid = Grid.init({
	            holder:'userList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/user/get_users',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        grid.onfilled(function(data){
        	grid.data = data;
        	if(data.in_balance=='-0.00')data.in_balance='0';
        	if(data.out_balance=='-0.00')data.out_balance='0';
        	if(data.ally_balance=='-0.00')data.ally_balance='0';
        	$('.in_balance').html(data.in_balance);
        	$('.out_balance').html(data.out_balance);
        	$('.ally_balance').html(data.ally_balance);
        	$('.ibtn').tooltip();
        });
        
        
        /* 数据搜索 */
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
            	pageSize = 20;
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
            	org_id: org_id,
        		search_text: txt,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        /* 搜索 */
	    $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        require('validate');

        /* 修改-dialog */
        $(document).on('click', '.editbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), org_id = $tr.attr('org_id');
        	var $dlg = $dialog({
                title: '修改用户信息',
                content: $('.pop-inofedit').clone().show()[0],
                width: '520px',
                onshow: function(){
                	var $node = $(this.node);
                	$('[name=name]',$node).val($('.org_name',$tr).text());
                	$('[name=phone]',$node).val($('.org_phone',$tr).text());
                	$('[name=email]',$node).val($('.org_email',$tr).text());
        			$('[name=description]',$node).val($('.org_description',$tr).text());
        			$node.initUI();
            	},
            	okValue: '确定',
            	ok: function(){
            		var $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		$ajax.ajax({
            			url : '/trp/user/do_modify/',
                		data: JSON.stringify({
                			org_id: org_id,
                			name: $('[name=name]',$node).val(),
                			phone: $('[name=phone]',$node).val(),
                			email: $('[name=email]',$node).val(),
                			description: $('[name=description]',$node).val()
        				}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
	                    	$dialog.alert('修改用户信息成功！','success');
	                    	filterData(semi.utils.gridPage(grid));
                        },
                        error: function(){
                        	$dlg.close().remove();
	                    	$dialog.alert('修改用户信息失败，请稍后重试！','warning');
                        }
                	 });
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        });

        /* 重置密码-dialog */
        $(document).on('click', '.resetbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), user_id = $tr.attr('user_id');
        	var $dlg = $dialog({
                title: '重置密码',
                content: $('.pop-resetpwd').clone().show()[0],
                width: '540px',
                onshow: function(){
                	$(this.node).find('[name=password]').addClass('resetpwd');
                },
                okValue: '确定',
                ok: function(){
            		var $node = $(this.node);
            		if(!$('form',$node).valid())return false;
	        		$ajax.ajax({
	        			url : '/trp/user/reset_password/',
	            		data: JSON.stringify({
	            			user_id: user_id,
	            			password: $.trim($('[name=password]',$node).val()),
	            			password_confirm: $.trim($('[name=password_confirm]',$node).val())
	    				}),
	            		contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
	                    success: function(data){
	                    	$dlg.close().remove();
	                    	$dialog.alert('重置密码成功！','success');
	                    },
	                    error: function(data){
                    		$dlg.close().remove();
                    		$dialog.alert('重置密码失败，请稍后重试！','warning');
	                    }
	            	 });
	            	return false;
	            },
	            cancelValue: '取消',
	            cancel: true
            }).showModal();
        });
        
        var updatebalance= function(callback){
			 $ajax.ajax({
        		 url: '/trp/organization/get_organization',
        		 data: JSON.stringify({
         			org_id: org_id,
 				 }),
         		 contentType : "application/json",
                 type : 'POST',
                 dataType : 'json',
        		 success: function(data){
        			 if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this,data);
        		 },
        		 error: function(data){
        			 seajs.log('获取balance失败！')
        			 seajs.log(data)
        		 }
        	 });
        };
        /* 账户充值 */
        $(document).on('click', '#btn-recharge', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), org_id = $('[name=org_id]').val();
        	var $dlg = $dialog({
                title: '账户充值',
                content: $('.pop-recharge').clone().show()[0],
                width: '500px',
                okValue: '确定',
                ok: function(){
	            	var $node = $(this.node);
	            	if(!$('form',$node).valid())return false;
	        		$ajax.ajax({
	        			url : '/trp/organization/do_charge/',
	            		data: JSON.stringify({
	            			org_id: org_id,
	            			charge_seq: $('[name=charge_seq]').val(),
	            			in_balance: $('[name=in_balance]',$node).val(),
	            			out_balance: $('[name=out_balance]',$node).val(),
	            			ally_balance: $('[name=ally_balance]',$node).val()
	    				}),
	            		contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
	                    success: function(data){
	                    	$('[name=charge_seq]').val(data.charge_seq);
	                    	$dlg.close().remove();
	                    	$dialog.alert('账户充值成功！','success');
	                    	updatebalance(function(data){
	                    		if(data.in_balance=='-0.00')data.in_balance='0';
	                        	if(data.out_balance=='-0.00')data.out_balance='0';
	                        	if(data.ally_balance=='-0.00')data.ally_balance='0';
	                    		$('.in_balance').html(data.in_balance);
	                    		$('.out_balance').html(data.out_balance);
	                    		$('.ally_balance').html(data.ally_balance);
	                    	});
	                    },
	                    error: function(data){
                    		$dlg.close().remove();
                    		$dialog.alert('账户充值失败，请稍后重试！','warning');
	                    }
	            	 });
	            	return false;
	            },
	            cancelValue: '取消',
	            cancel: true
            }).showModal();
        });
        
        /** 充值记录 **/
        $(document).on('click', '#btn-chargelist', function(){
        	var $dlg = $dialog({
                title: '充值记录',
                content: $('.pop-chargelist').clone().show()[0],
                width: '800px',
                onshow: function(){
                	var $d = this, $node = $(this.node);
                	$('.grid',$node).attr('id','chargeList');
                	var  chargeBodyTemplate= ['<tr>',
          		    	                    '<td class="txtc">{organization}</td>',
          		    	                    '<td class="txtc" >{time}</td>',
          		    	                    '<td class="txtr" >{in_balance}</td>',
          		    	                    '<td class="txtr" >{out_balance}</td>',
          		    	                    '<td class="txtr" >{ally_balance}</td>',
          		    	                    '<td class="txtc">{charger}</td>',
          	    	                    '</tr>'].join('');
                  
	                  var chargeLogGrid = Grid.init({
	          	            holder:'chargeList',
	          	            bodyTemplate:chargeBodyTemplate,
	          	            dataSource:'/trp/paylog/get_paylogs',
	          	            pageTemplate:semi.grid.pageTemplate,
	          	            sendOnPageSize: true
	          	    	}).send({
	                      	org_id: org_id,
	                  		pageSize: 20,
	                  		pageNo: 1
	                  	});
                },
                button:[{value:'关闭'}]
            }).showModal();
        });
        
        /* 新增用户-dialog */
        $('#btn-createuser').on('click', function(){
        	var $dlg = $dialog({
                title: '新增用户',
                width: '500px',
            	onshow: function(){
            		var $d = this, $node = $($d.node);
            		$d.content($('.pop-createuser').clone().show()[0]);
            		$('[name=type]',$node).select2({allowClear: true});
            		$('[name=password]',$node).addClass('newpwd');
            		$('[name=username]',$node).on('focus', function(){
            			$(this).removeClass('error').siblings('label.error').remove();
            		});
            		setTimeout(function(){
            			$('form',$node)[0].reset();
            		},100);
            	},
            	okValue: '确定',
            	ok: function(){
            		var $node = $(this.node);
        			$ajax.ajax({
        				url: '/trp/user/check_username/',
        				data: JSON.stringify({
        					username: $('[name=username]',$node).val()
        				}),
        				contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
        				success: function(){
        					$('form',$node).valid();
        					$('[name=username]',$node).addClass('error').after('<label for="username" generated="true" class="error">用户名已被占用</label>');
        				},
        				error: function(){
        					if(!$('form',$node).valid())return false;
                    		$ajax.ajax({
                    			url : '/trp/user/do_create/',
                        		data: JSON.stringify({
                            		name: $('[name=username]',$node).val(),
                            		phone: $('[name=phone]',$node).val(),
                            		email: $('[name=email]',$node).val(),
                            		type: $('[name=type]',$node).val(),
                            		password: $('[name=password]',$node).val(),
                            		password_confirm: $('[name=password_confirm]',$node).val(),
                            		org_id:org_id,
                            		description: $('[name=description]',$node).val()
                				}),
                        		contentType : "application/json",
                                type : 'POST',
                                dataType : 'json',
                                success: function(){
                                	$dlg.close().remove();
                                	$dialog.alert('新增用户成功！','success');
                                	filterData();
                                },
                                error: function(){
                                	$dlg.close().remove();
                                	$dialog.alert('新增用户失败，请稍后重试！','warning');
                                }
                        	 });
        				}
        			});
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        });
        
        if(semi.utils.isEmpty($('.in_balance').html()))$('.in_balance').html(0);
        if(semi.utils.isEmpty($('.out_balance').html()))$('.out_balance').html(0);
        if(semi.utils.isEmpty($('.ally_balance').html()))$('.ally_balance').html(0);
        
    });
});